//
//  NewOrderVC.swift
//  Employee
//
//  Created by swordjoy on 2017/3/27.
//  Copyright © 2017年 remotevillage. All rights reserved.
//

import UIKit
import Photos

class NewOrderVC:BaseVC {

    var refreshBefore: VoidClosure?
    
    fileprivate var assets: [PHAsset] = [] {
        didSet {
            runOnMainThread {
                self.newOrderV.assets = self.assets
            }
        }
    }
    fileprivate var assetIdentifier = ""
  
    fileprivate var model = NewOrderModel()

    fileprivate var contentScrollV: UIScrollView!

    fileprivate var newOrderV: NewOrderV!
    fileprivate var selectInfosV: SelectInfosV!
    fileprivate var finishButton: ObserveButton!
    fileprivate var selectImageV: SelectImagePopV!
    
    fileprivate var helper = NewOrderHelper()
  
    override func viewDidLoad() {
        super.viewDidLoad()

        create()
        closure()
    }
  
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBar.setBackgroundImage(GlobalConfig.BGWhiteImage, for: .default)

        GlobalConfig.baiduStatisticsPageViewStart("新建工单")
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        GlobalConfig.baiduStatisticsPageViewEnd("新建工单")
    }

}

// MARK: - action

extension NewOrderVC {
  
  fileprivate func takePhoto() {
    
    if assets.count >= 4 {
      SJHint.show("你已经选择了四张啦")
      return
    }
    
    if GlobalConfig.isAuthorizationVideo() {
      let imagePicker = UIImagePickerController()
      imagePicker.delegate = self
      imagePicker.allowsEditing = true
      imagePicker.sourceType = .camera
      self.present(imagePicker, animated: true, completion: nil)
    }
    
  }
  
  @objc fileprivate func finishAction() {
    SJApp.endEdit()
    SJApp.showHUD()
    // 没有图片
    if assets.isEmpty {
      let _ = WorkorderRequest.shared.newOrder(by: self.model) {
        self.refreshBefore?()
        self.navigationController?.popViewController(animated: true)
        SJHint.show("新建工单成功!")
      }
      return
    }
    
    runInBackground { 
        var tempDatas: [Data] = []
        let uploadImages = PhotoHelper.fetchOriginalPhotos(with: self.assets)
        
        for uploadImage in uploadImages {
            tempDatas.append(uploadImage.uploadData)
        }
        
        let _ = FileRequest.shared.uploadImages(datas: tempDatas, progressClosure: { (progress) in
        }) { (ids) in
            self.model.imageModels = ids
            let _ = WorkorderRequest.shared.newOrder(by: self.model) {
                self.refreshBefore?()
                self.navigationController?.popViewController(animated: true)
                SJHint.show("新建工单成功!")
            }
        }
    }
  }
}

extension NewOrderVC: PhotoPickerDelegate {
    func photoPickerDidFinishSelected(_ assets: [PHAsset]) {
        self.assets += assets
    }
}

extension NewOrderVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  
  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else {
        return
    }
    
    PHPhotoLibrary.shared().performChanges({
        let request = PHAssetChangeRequest.creationRequestForAsset(from: image)
        self.assetIdentifier = request.placeholderForCreatedAsset?.localIdentifier ?? ""
    }) { (finish, error) in
        if nil != error {
            runOnMainThread {
                SJHint.show("获取照片失败, 请重新拍摄")
                picker.dismiss(animated: true) { }
            }
            return
        }
        else {
            let tempAssets = PHAsset.fetchAssets(withLocalIdentifiers: [self.assetIdentifier], options: nil)
            guard let asset = tempAssets.firstObject else {
                runOnMainThread {
                    SJHint.show("获取照片失败, 请重新拍摄")
                    picker.dismiss(animated: true) { }
                }
                return
            }
            self.assets.append(asset)
            runOnMainThread({
                picker.dismiss(animated: true) { }
            })
            
        }
    }

  }
  
  func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    runOnMainThread({
        picker.dismiss(animated: true) {
          
        }
    })
  }
  
}

// MARK: - fileprivate

extension NewOrderVC {
  
  fileprivate func observeButtonState() {
    self.finishButton.isSelected = NewOrderHelper.verifyInput(model: self.model)
  }
  
  fileprivate func closure() {
    newOrderV.addPhotoClosure = { [unowned self] in
      SJApp.endEdit()
      self.selectImageV.show(in: self.navigationController!.view!)
    }
    
    newOrderV.deleteClosure = { [unowned self] index in
      SJApp.endEdit()
      self.assets.remove(at: index)
    }
    
    newOrderV.cellDidClickAction = { [unowned self] index in
      SJApp.endEdit()
        
        let viewer = PhotoViewer(with: self.assets, enterIndex: index)
        self.navigationController?.pushViewController(viewer, animated: true)
    }
    
    
    // 标题编辑完毕,判断完成button
    newOrderV.titleDidEndEditing = { [unowned self] (text) in
      self.model.title = text
      self.observeButtonState()
    }
    
    // 内容编辑完毕,判断完成button
    newOrderV.contentDidEndEditing = { [unowned self] (text) in
      self.model.content = text
      self.observeButtonState()
    }
    
    
    selectInfosV.selectInfoClick = { [unowned self] type in
      
      SJApp.endEdit()
      
      switch type {
      case .orderType:
        
        let treePicker = SJTreePicker()
        treePicker.style = .category
        treePicker.title = "选择工单分类"
        treePicker.show(in: self.navigationController!.view)
        
        treePicker.didSelectClosure = { one, two in
          
          if two.0.isEmpty {
            self.model.categoryId = one.0
            self.selectInfosV.updateDetail(0, detail: one.1)
          }
          else {
            self.model.categoryId = two.0
            self.selectInfosV.updateDetail(0, detail: "\(one.1) \(two.1)")
          }

          if one.1.isEmpty {
            self.selectInfosV.updateDetail(0, detail: "选择")
          }
          
          self.observeButtonState()
        }
        
        let _ = WorkorderRequest.shared.getWorkOrderCategory(success: { (tree) in
          
          if tree.children.isEmpty {
            SJHint.show("请先在后台添加分类")
            return
          }
          
          treePicker.tree = tree
          
        })
        
      case .priority:
        
        let treePicker = SJTreePicker()
        treePicker.style = .priority
        treePicker.title = "选择优先级"
        let prioritys = Priority.array(from: [("NORMAL", "一般"), ("URGENT", "紧急"), ("VERY_URGENT", "非常紧急")])
        treePicker.prioritys = prioritys
        treePicker.show(in: self.navigationController!.view)
        
        treePicker.didSelectClosure = { one, _ in
          
          self.model.priorityLevel = one.0
          
          self.selectInfosV.updateDetail(1, detail: one.1)
          
          if one.1.isEmpty { self.selectInfosV.updateDetail(1, detail: "选择") }
          self.observeButtonState()
        }
        
      case .rule:
        
        let treePicker = SJTreePicker()
        treePicker.style = .rule
        treePicker.title = "选择派单规则"
        treePicker.show(in: self.navigationController!.view)
        
        treePicker.didSelectClosure = { (one, two) in
          
          if one.0 == "DEFAULT" {
            self.model.accept = "DEFAULT"
            self.model.acceptStaffId = ""
            self.model.acceptOrgId = ""
            self.selectInfosV.updateDetail(2, detail: one.1)
            self.observeButtonState()
            return
          }
          
          self.model.acceptStaffId = two.0
          self.model.acceptOrgId = one.0
          
          if two.0.isEmpty {
            self.model.accept = "ORGANIZATION"
            self.selectInfosV.updateDetail(2, detail: one.1)
          } else {
            self.model.accept = "STAFF"
            self.selectInfosV.updateDetail(2, detail: "\(one.1) \(two.1)")
          }
          
          if one.1.isEmpty { self.selectInfosV.updateDetail(2, detail: "选择") }
          self.observeButtonState()
        }
        
        let department = Department(name: "默认分配", id: "DEFAULT", staffs: [])
        
        let _ = WorkorderRequest.shared.getOrganization(success: { (departments) in
          var temps = departments
          temps.insert(department, at: 0)
          treePicker.departments = temps
        })
        
      }
    }
    
    selectImageV.takePhotoClosure = { [unowned self] in self.takePhoto() }
    
    selectImageV.selectClosure = { [unowned self] in
        let photoPicker = PhotoPicker(selectedCount: self.assets.count, maxCount: 4, delegate: self)
        self.navigationController?.pushViewController(photoPicker, animated: true)
    }
    
  }
  
  fileprivate func create() {
    view.backgroundColor = GlobalConfig.BGWhiteColor
    title = "新建工单"
    addBackItem()
    
    finishButton = ObserveButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
    finishButton.setTitle("完成", for: .normal)
    finishButton.addTarget(self, action: #selector(finishAction), for: .touchUpInside)
    finishButton.isSelected = false
    finishButton.contentHorizontalAlignment = .right
    let rightItem = UIBarButtonItem(customView: finishButton)
    navigationItem.rightBarButtonItem = rightItem
    
    contentScrollV = UIScrollView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.noNavBarHeight))
    view.addSubview(contentScrollV)
    contentScrollV.backgroundColor = UIColor.clear
    contentScrollV.alwaysBounceVertical = false
    contentScrollV.showsVerticalScrollIndicator = false
    
    newOrderV = NewOrderV(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 375))
    contentScrollV.addSubview(newOrderV)
    
    selectInfosV = SelectInfosV(frame: CGRect(x: 0, y: 375, width: UIScreen.width, height: 250))
    contentScrollV.addSubview(selectInfosV)
    
    if UIScreen.noNavBarHeight > 625 {
      contentScrollV.contentSize = CGSize(width: UIScreen.width, height: UIScreen.noNavBarHeight)
    } else {
      contentScrollV.contentSize = CGSize(width: UIScreen.width, height: 625)
    }
    
    selectImageV = SelectImagePopV(frame: UIScreen.main.bounds)
  }
}
